using System.Security.Claims;
using Microsoft.AspNetCore.Http;

namespace Terra.Core.Infrastructure.Security;

/// <summary>
/// 当前用户服务实现
/// </summary>
public class CurrentUser : ICurrentUser
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="httpContextAccessor">HTTP上下文访问器</param>
    public CurrentUser(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    /// <summary>
    /// 获取当前用户ID
    /// </summary>
    public Guid? Id
    {
        get
        {
            var id = _httpContextAccessor.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            return id != null ? Guid.Parse(id) : null;
        }
    }

    /// <summary>
    /// 获取当前用户名
    /// </summary>
    public string Name => _httpContextAccessor.HttpContext?.User?.Identity?.Name ?? "system";

    /// <summary>
    /// 判断当前用户是否已认证
    /// </summary>
    public bool IsAuthenticated => _httpContextAccessor.HttpContext?.User?.Identity?.IsAuthenticated ?? false;
}